package com.sangu.dianxiu.ui;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.android.volley.VolleyError;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;
import com.sangu.dianxiu.BaseApp;
import com.sangu.dianxiu.ICallBack;
import com.sangu.dianxiu.R;
import com.sangu.dianxiu.bean.basedata.UploadFileEntity;
import com.sangu.dianxiu.bean.user.AddOrderEntity;
import com.sangu.dianxiu.config.Constants;
import com.sangu.dianxiu.utils.BitmapUtils;
import com.sangu.dianxiu.utils.RecordUtil;
import com.sangu.dianxiu.utils.RepairOrderManager;
import com.sangu.dianxiu.utils.RepairTypeManager;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.UUID;

import cz.msebera.android.httpclient.Header;

public class OrderActivity extends BaseActivity implements View.OnTouchListener{
    private Bitmap bitmap1;                 //拍照获得的bitmap1
    private Bitmap bitmap2;                 //拍照获得的bitmap2
    private Bitmap bitmap3;                   //拍照获得的bitmap3
    private int projectId;                  //项目id
    private String addressId;               //地址id
    private String contactId;              //联系人id
    private long img1Id;                    //第一张图片的id
    private long img2Id;                    //第二张图片的id
    private long img3Id;                    //第三张图片的id
    private long voiceId;                   //录音的id
    private boolean isImg1Upload=false;        //用来判断第一张图片有没有上传成功
    private boolean isImg2Upload=false;         //用来判断第二张图片有没有上传成功
    private boolean isImg3Upload=false;         //用来判断第三张图片有没有上传成功
    private boolean isVoiceUpload=false;        //用来判断语音有没有上传成功
    private String projectName;                 //项目的名字
    private String address;                     //地址
    private String contactName;                 //联系人姓名
    private String repairTime;                  //预约维修时间
    private boolean isFromCameral=true;         //判断是从照相机拍摄获得的还是从相册中选择的图片
    private Dialog reccordingDialog;            //正在录音的显示界面
    private Dialog pictureDialog;
    private AsyncHttpClient httpClient=new AsyncHttpClient();           //使用AsyncHttpClient进行文件上传
    private RepairOrderManager orderManager=new RepairOrderManager();   //使用此类进行网络数据请求
    @ViewInject(R.id.tv_activity_order_projectid)                       //使用xutils注解框架，这样就不用findviewbyid了
    private TextView tvProjectId;
    @ViewInject(R.id.iv_activity_order_project_select)
    private ImageView ivProjectSelect;
    @ViewInject(R.id.tv_activity_order_project_addrid)
    private TextView tvAddrId;
    @ViewInject(R.id.iv_activity_order_addr_select)
    private ImageView ivAddrSelect;
    @ViewInject(R.id.tv_activity_order_project_timeid)
    private TextView tvTimeId;
    @ViewInject(R.id.iv_activity_order_time_select)
    private ImageView ivTimeSelect;
    @ViewInject(R.id.tv_activity_order_project_contactid)
    private TextView tvContactId;
    @ViewInject(R.id.iv_activity_order_contact_select)
    private ImageView ivContactSelect;
    @ViewInject(R.id.et_activity_order_project_repairerno)
    private EditText etRepairerNo;
    @ViewInject(R.id.rl_activity_order_picture1)
    private RelativeLayout rlPicture1;
    @ViewInject(R.id.rl_activity_order_picture2)
    private RelativeLayout rlPicture2;
    @ViewInject(R.id.rl_activity_order_picture3)
    private RelativeLayout rlPicture3;
    @ViewInject(R.id.rl_activity_order_reccord)
    private RelativeLayout rlReccord;
    @ViewInject(R.id.iv_activity_order_picture1)
    private ImageView ivPicture1;
    @ViewInject(R.id.iv_activity_order_picture2)
    private ImageView ivPicture2;
    @ViewInject(R.id.iv_activity_order_picture3)
    private ImageView ivPicture3;
    @ViewInject(R.id.tv_activity_order_reccord_time)
    private TextView tvReccordTime;
    @ViewInject(R.id.ll_activity_order_add_picture1)
    private LinearLayout llAddPicture1;
    @ViewInject(R.id.ll_activity_order_add_picture2)
    private LinearLayout llAddPicture2;
    @ViewInject(R.id.ll_activity_order_add_picture3)
    private LinearLayout llAddPicture3;
    @ViewInject(R.id.ll_activity_order_add_record)
    private LinearLayout llAddReccord;
    @ViewInject(R.id.tv_activity_add_reccord)
    private TextView tvAddReccord;
    @ViewInject(R.id.et_activity_order_detail)
    private EditText etDetail;
    @ViewInject(R.id.rl_activity_order_reccording)
    private RelativeLayout rlReccording;
    @ViewInject(R.id.iv_activity_volume)
    private ImageView ivVolume;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        setContentView(R.layout.activity_order);
        ViewUtils.inject(this);                                 //如果没有此行，则xutils的注解不会生效
        projectName=getIntent().getStringExtra("name");         //从projectactivity获得传过来的数据
        projectId=getIntent().getIntExtra("projectId", 0);
        tvProjectId.setText(projectName);
        llAddReccord.setOnTouchListener(this);                  //给录音按钮设置触摸监听事件
        init();
    }

    private void init() {
        if(BaseApp.isModifying)                                 //判断是否是从修改订单界面跳到该activity的，如果是，则要从修改订单activity接收相应的数据
        {
            Intent intent=null;
            if((intent=getIntent())!=null)
            {
                String projectName=intent.getStringExtra("projectName");
                String projectId=intent.getStringExtra("projectId");
                String addr=intent.getStringExtra("addr");
                String reason=intent.getStringExtra("reason");
                String repairTime=intent.getStringExtra("repairTime");
                String orderNo=intent.getStringExtra("orderNo");
                Bitmap bitmap1=intent.getParcelableExtra("bitmap1");
                Bitmap bitmap2=intent.getParcelableExtra("bitmap2");
                Bitmap bitmap3=intent.getParcelableExtra("bitmap3");
                String reccordPath=intent.getStringExtra("voicePath");
                String reccordTime=intent.getStringExtra("reccordTime");
                tvProjectId.setText(projectName);
                tvTimeId.setText(repairTime);
                tvAddrId.setText(addr);
                etDetail.setText(reason);
                if(bitmap1!=null)
                {
                    rlPicture1.setVisibility(View.VISIBLE);
                    llAddPicture1.setVisibility(View.GONE);
                    ivPicture1.setImageBitmap(bitmap1);
                }
                if (bitmap2 != null) {
                    rlPicture2.setVisibility(View.VISIBLE);
                    llAddPicture2.setVisibility(View.GONE);
                    ivPicture2.setImageBitmap(bitmap2);
                }
                if (bitmap3 != null) {
                    rlPicture3.setVisibility(View.VISIBLE);
                    llAddPicture3.setVisibility(View.GONE);
                    ivPicture3.setImageBitmap(bitmap3);
                }
                if(reccordPath!=null)
                {
                    llAddReccord.setVisibility(View.GONE);
                    rlReccord.setVisibility(View.VISIBLE);
                    tvReccordTime.setText(reccordTime + "”");
                }

            }
            BaseApp.isModifying=false;
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==Constants.REQUEST_CODE_SELECT_REPAIR_PROJECT)               //获得选择的项目
        {
            if(data!=null)
            {
                projectName=data.getStringExtra("name");
                projectId=data.getIntExtra("projectId", 0);

            }
        }
        if(requestCode==Constants.REQUEST_CODE_ADDRESS_SELECT)                      //获得选择的地址
        {
            addressId=data.getStringExtra("addrId");
            address=data.getStringExtra("addr");
            tvAddrId.setText(address);
        }
        if (requestCode == Constants.REQUEST_CODE_CONTACT_SELECT)                       //获得选择的联系人
        {
            contactId=data.getStringExtra("contactId");
            contactName=data.getStringExtra("contactName");
            tvContactId.setText(contactName);
        }
        if (requestCode == Constants.REQUEST_CODE_CAMERAL1) {                           //判断是否是第一张图片
            if (isFromCameral) {                                                        //判断是否来自照相机
                if(resultCode== Activity.RESULT_CANCELED)                               //如果用户启动了相机后点了返回键，则要判断，避免因此而程序crash
                {
                    return;
                }else{
                    bitmap1 = (Bitmap) data.getExtras().get("data");                    //从相机拍摄的照片中获得bitmap
                }

            } else {
                if (resultCode == RESULT_OK && null != data) {                          //如果是从相册中选择的则进行相应的处理
                    Uri selectedImage = data.getData();
                    String[] filePathColumn = { MediaStore.Images.Media.DATA };
                    Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
                    cursor.moveToFirst();
                    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                    String picturePath = cursor.getString(columnIndex);
                    cursor.close();
                    bitmap1= BitmapUtils.convertToBitmap(picturePath, ivPicture1.getLayoutParams().width, ivPicture1.getLayoutParams().height);
                }
            }
            if (bitmap1 != null) {                              //如果获得的bitmap不为空则改变相应的视图
                rlPicture1.setVisibility(View.VISIBLE);
                llAddPicture1.setVisibility(View.GONE);
                ivPicture1.setImageBitmap(bitmap1);
            }
            pictureDialog.dismiss();
        }
        if (requestCode == Constants.REQUEST_CODE_CAMERAL2) {
            if (isFromCameral) {
                if(resultCode==Activity.RESULT_CANCELED)
                {
                    return;
                }else{
                    bitmap2 = (Bitmap) data.getExtras().get("data");
                }

            } else {
                if (resultCode == RESULT_OK && null != data) {
                    Uri selectedImage = data.getData();
                    String[] filePathColumn = { MediaStore.Images.Media.DATA };
                    Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
                    cursor.moveToFirst();
                    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                    String picturePath = cursor.getString(columnIndex);
                    cursor.close();
                    bitmap2 = BitmapUtils.convertToBitmap(picturePath, ivPicture2.getLayoutParams().width, ivPicture2.getLayoutParams().height);
                }
            }
            if (bitmap2 != null) {
                rlPicture2.setVisibility(View.VISIBLE);
                llAddPicture2.setVisibility(View.GONE);
                ivPicture2.setImageBitmap(bitmap2);
            }
            pictureDialog.dismiss();
        }
        if (requestCode == Constants.REQUEST_CODE_CAMERAL3) {
            if (isFromCameral) {
                if(resultCode==Activity.RESULT_CANCELED)
                {
                    return;
                }else{
                    bitmap3 = (Bitmap) data.getExtras().get("data");
                }

            } else {
                if (resultCode == RESULT_OK && null != data) {
                    Uri selectedImage = data.getData();
                    String[] filePathColumn = { MediaStore.Images.Media.DATA };
                    Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
                    cursor.moveToFirst();
                    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                    String picturePath = cursor.getString(columnIndex);
                    cursor.close();
                    bitmap3 = BitmapUtils.convertToBitmap(picturePath, ivPicture1.getLayoutParams().width, ivPicture1.getLayoutParams().height);
                }
            }
            if (bitmap3 != null) {
                rlPicture3.setVisibility(View.VISIBLE);
                llAddPicture3.setVisibility(View.GONE);
                ivPicture3.setImageBitmap(bitmap3);
            }
            pictureDialog.dismiss();
        }

    }

    //使用xutils的点击事件注解，这样就不用setonclicklistener了
    @OnClick({R.id.iv_activity_order_back,R.id.iv_activity_order_project_select,R.id.iv_activity_order_addr_select,R.id.iv_activity_order_time_select,
            R.id.iv_activity_order_contact_select,R.id.iv_activity_order_delete1,R.id.iv_activity_order_delete2,R.id.iv_activity_order_delete3,
            R.id.iv_activity_order_delete4,R.id.ll_activity_order_add_picture1, R.id.ll_activity_order_add_picture2, R.id.ll_activity_order_add_picture3,
            R.id.btn_activity_order_submit})
    public void onClick(View view)
    {
        Intent intent;
        switch (view.getId())
        {
            case R.id.iv_activity_order_back:
                finish();
                break;
            case R.id.iv_activity_order_project_select:
                intent=new Intent(this,RepairProjectActivity.class);            //跳到项目选择activity
                startActivityForResult(intent,Constants.REQUEST_CODE_SELECT_REPAIR_PROJECT);
                break;
            case R.id.iv_activity_order_addr_select:
                intent=new Intent(this,FrequentAddressActivity.class);          //跳到常用地址选择activity
                startActivityForResult(intent,Constants.REQUEST_CODE_ADDRESS_SELECT);
                break;
            case R.id.iv_activity_order_time_select:                            //进行时间选择

                break;
            case R.id.iv_activity_order_contact_select:
                intent=new Intent(this,FrequentContactsActivity.class);
                startActivityForResult(intent,Constants.REQUEST_CODE_CONTACT_SELECT);       //跳到常用联系人选择activity
                break;
            case R.id.ll_activity_order_add_picture1:                                       //添加第一张图片
                showSelectDialog(Constants.REQUEST_CODE_CAMERAL1);
                break;
            case R.id.ll_activity_order_add_picture2:
                showSelectDialog(Constants.REQUEST_CODE_CAMERAL2);                          //添加第二张图片
                break;
            case R.id.ll_activity_order_add_picture3:
                showSelectDialog(Constants.REQUEST_CODE_CAMERAL3);                          //添加第三张图片
                break;
            case R.id.iv_activity_order_delete1:                                            //删除图片1
                bitmap1=null;
                llAddPicture1.setVisibility(View.VISIBLE);
                rlPicture1.setVisibility(View.GONE);
                break;
            case R.id.iv_activity_order_delete2:                                            //删除图片2
                bitmap2=null;
                llAddPicture2.setVisibility(View.VISIBLE);
                rlPicture2.setVisibility(View.GONE);
                break;
            case R.id.iv_activity_order_delete3:                                            //删除图片3
                bitmap3=null;
                llAddPicture3.setVisibility(View.VISIBLE);
                rlPicture3.setVisibility(View.GONE);
                break;
            case R.id.iv_activity_order_delete4:                                        //删除语音
                recordTime=0;
                rlReccord.setVisibility(View.GONE);
                llAddReccord.setVisibility(View.VISIBLE);
                break;
            case R.id.btn_activity_order_submit:                            //当点击提交的时候要进行判断添加的图片和语音，若没有添加，则要设置上传标志为已上传，下同
                if(bitmap1==null)
                {
                    isImg1Upload=true;
                }
                if(bitmap2==null)
                {
                    isImg2Upload=true;
                }
                if(bitmap3==null)
                {
                    isImg3Upload=true;
                }
                if(reccordPath==null)
                {
                    isVoiceUpload=true;
                }
                if(BaseApp.isLogin==false)              //如果没有登录则提示用户登录
                {
                    Toast.makeText(this,"请先登录",Toast.LENGTH_SHORT).show();
                }else{
                    uploadFile();
                }
                break;
        }
    }
//上传文件
    private void uploadFile() {

        if(bitmap1!=null)
        {
            ByteArrayOutputStream baos1 = new ByteArrayOutputStream();
            ByteArrayInputStream is1=null;
            bitmap1.compress(Bitmap.CompressFormat.JPEG, 100, baos1);           //将图片压缩后进行上传
            is1= new ByteArrayInputStream(baos1.toByteArray());
            httpClient.post(Constants.URL_UPLOAD_FILE, getRequestParams(is1), new TextHttpResponseHandler() {
                @Override
                public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                }

                @Override
                public void onSuccess(int statusCode, Header[] headers, String responseString) {
                    String s=responseString;
                    UploadFileEntity entity=JSONObject.parseObject(responseString,UploadFileEntity.class);
                    if(entity.getRc()==0)
                    {
                        isImg1Upload=true;
                        img1Id=entity.getFileId();              //当上传成功后要从服务器获得返回的id，上传文件成功后提交订单要用到
                    }
                    if(isImg1Upload&&isImg2Upload&&isImg3Upload&&isVoiceUpload)
                    {
                        submit();                               //如果全部上传成功，则提交订单
                    }
                }
            });
        }
        if(bitmap2!=null)
        {
            ByteArrayOutputStream baos2 = new ByteArrayOutputStream();
            ByteArrayInputStream is2=null;
            bitmap2.compress(Bitmap.CompressFormat.JPEG, 100, baos2);
            is2= new ByteArrayInputStream(baos2.toByteArray());
            httpClient.post(Constants.URL_UPLOAD_FILE, getRequestParams(is2), new TextHttpResponseHandler() {
                @Override
                public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                }

                @Override
                public void onSuccess(int statusCode, Header[] headers, String responseString) {
                    String s=responseString;
                    UploadFileEntity entity=JSONObject.parseObject(responseString,UploadFileEntity.class);
                    if(entity.getRc()==0)
                    {
                        isImg2Upload=true;
                        img2Id=entity.getFileId();
                    }
                    if(isImg1Upload&&isImg2Upload&&isImg3Upload&&isVoiceUpload)
                    {
                        submit();
                    }
                }
            });
        }
        if(bitmap3!=null)
        {
            ByteArrayOutputStream baos3 = new ByteArrayOutputStream();
            ByteArrayInputStream is3 = null;
            bitmap3.compress(Bitmap.CompressFormat.JPEG,100,baos3);
            is3= new ByteArrayInputStream(baos3.toByteArray());
            httpClient.post(Constants.URL_UPLOAD_FILE, getRequestParams(is3), new TextHttpResponseHandler() {
                @Override
                public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                }

                @Override
                public void onSuccess(int statusCode, Header[] headers, String responseString) {
                    String s=responseString;
                    UploadFileEntity entity=JSONObject.parseObject(responseString,UploadFileEntity.class);
                    if(entity.getRc()==0)
                    {
                        isImg3Upload=true;
                        img3Id=entity.getFileId();
                    }
                    if(isImg1Upload&&isImg2Upload&&isImg3Upload&&isVoiceUpload)
                    {
                        submit();
                    }
                }
            });
        }
        if(reccordPath!=null)
        {
            RequestParams params4=new RequestParams();
            params4.put("userId",BaseApp.user.getUserId()+"");
            params4.put("fileName","VOICE_"+new SimpleDateFormat("yyyyMMdd HHmmss").format(new Date()) + ".amr");
            try {
                params4.put("file", new File(reccordPath));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            httpClient.post(Constants.URL_UPLOAD_FILE, params4, new TextHttpResponseHandler() {
                @Override
                public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                }

                @Override
                public void onSuccess(int statusCode, Header[] headers, String responseString) {
                    String s = responseString;
                    UploadFileEntity entity = JSONObject.parseObject(responseString, UploadFileEntity.class);
                    if (entity.getRc() == 0) {
                        isVoiceUpload = true;
                        voiceId = entity.getFileId();
                    }
                    if (isImg1Upload && isImg2Upload && isImg3Upload && isVoiceUpload) {
                        submit();
                    }
                }
            });
        }


    }
    //获得数据请求的参数
    public  RequestParams getRequestParams(ByteArrayInputStream is)
    {
        RequestParams params=new RequestParams();
        params.put("userId",BaseApp.user.getUserId()+"");
        params.put("fileName","IMG_" + new SimpleDateFormat("yyyyMMdd HHmmss").format(new Date()) + ".jpeg");
        params.put("file", is);
        return params;
    }
    //提交订单
    private void submit() {
        HashMap<String,String> map=new HashMap<>();
        map.put("userId", BaseApp.user.getUserId()+"");
        map.put("itemId",projectId+"");
        map.put("addrId",addressId);
        long time=System.currentTimeMillis();
        map.put("orderTime",time+"");
        map.put("contactId",contactId);
        map.put("repairerNO",101+"");
        map.put("relatedOrderId","");
        map.put("imgId1",img1Id+"");
        map.put("imgId2",img2Id+"");
        map.put("imgId3",img3Id+"");
        map.put("voiceId",voiceId+"");
        map.put("text",etDetail.getText().toString());
        orderManager.add(map, new ICallBack() {
            @Override
            public void onSuccess(String string) {
                String s=string;
                AddOrderEntity entity=JSONObject.parseObject(string,AddOrderEntity.class);
                if(entity.getRc()==0)
                {
                    Toast.makeText(OrderActivity.this,"提交成功",Toast.LENGTH_SHORT).show();
                }else{
                    Toast.makeText(OrderActivity.this,"提交失败",Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onError(VolleyError error) {

            }
        });
    }
    //显示选择图片界面
    private void showSelectDialog(final int requestCode) {
        View view = getLayoutInflater().inflate(R.layout.photo_choose_dialog, null);
        Button btnOpenPhotoLibrary= (Button) view.findViewById(R.id.btn_photo_choose_photo_library);
        Button btnOpenCameral= (Button) view.findViewById(R.id.btn_photo_choose_open_cameral);
        Button btnCancel= (Button) view.findViewById(R.id.btn_photo_choose_cancel);
        pictureDialog = new Dialog(this, R.style.transparentFrameWindowStyle);
        pictureDialog.setContentView(view, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT));
        Window window = pictureDialog.getWindow();
        // 设置显示动画
        window.setWindowAnimations(R.style.main_menu_animstyle);
        WindowManager.LayoutParams wl = window.getAttributes();
        wl.x = 0;
        wl.y = getWindowManager().getDefaultDisplay().getHeight();
        // 以下这两句是为了保证按钮可以水平满屏
        wl.width = ViewGroup.LayoutParams.MATCH_PARENT;
        wl.height = ViewGroup.LayoutParams.WRAP_CONTENT;

        // 设置显示位置
        pictureDialog.onWindowAttributesChanged(wl);
        // 设置点击外围解散
        pictureDialog.setCanceledOnTouchOutside(true);
        pictureDialog.show();
        btnOpenPhotoLibrary.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isFromCameral=false;
                Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(i, requestCode);
            }
        });
        btnOpenCameral.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isFromCameral=true;
                Intent intent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(intent, requestCode);
            }
        });
        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pictureDialog.dismiss();
            }
        });
    }
    //录音
    private double recordTime=0.0;          //录音时常
    private double volume;                  //录音音量
    private String reccordPath=null;           //录音文件存储路径
    private static final String PATH = "/sdcard/Record/";       //录音文件存储根目录
    private RecordUtil recordUtil;              //录音工具
    private boolean isReccording=false;
    private Handler recordHandler=new Handler()
    {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what)
            {
                case 1:
                    if(volume<200.0){
                        ivVolume.setImageResource(R.mipmap.v1);             //设置录音音量，并动态改变录音音量界面
                    }else if(volume>200.0&&volume<400.0){
                        ivVolume.setImageResource(R.mipmap.v2);
                    } else if(volume>400.0&&volume<800.0){
                        ivVolume.setImageResource(R.mipmap.v3);
                    } else if(volume>800.0&&volume<1600.0){
                        ivVolume.setImageResource(R.mipmap.v4);
                    }else if(volume>1600.0&&volume<3200.0){
                        ivVolume.setImageResource(R.mipmap.v5);
                    }else if(volume>3200.0&&volume<6400.0){
                        ivVolume.setImageResource(R.mipmap.v6);
                    }else if(volume>6400.0&&volume<12800.0){
                        ivVolume.setImageResource(R.mipmap.v7);
                    }
                    break;
            }
        }
    };
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (event.getAction())
        {
            case MotionEvent.ACTION_DOWN:
                reccordPath=PATH + UUID.randomUUID().toString()+ ".amr";
                recordUtil=new RecordUtil(reccordPath);
                tvAddReccord.setText("松开结束");
                View dialogView=getLayoutInflater().inflate(R.layout.reccord_dialog_layout,null);
                ivVolume= (ImageView) dialogView.findViewById(R.id.iv_activity_volume);
                reccordingDialog=new Dialog(this,R.style.mystyle);
                reccordingDialog.setContentView(dialogView);
                reccordingDialog.show();
                try {
                    recordUtil.start();
                    isReccording=true;
                    new Thread(new Runnable() {                     //启动一个新线程来不断获得录音音量，以及计算录音时间
                        @Override
                        public void run() {
                            try {
                                while (isReccording) {
                                    Thread.sleep(100);
                                    recordTime += 0.1;
                                    volume = recordUtil.getAmplitude();
                                    recordHandler.sendEmptyMessage(1);
                                }
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }).start();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                break;
            case MotionEvent.ACTION_UP:             //当松开时停止录音
                try {
                    isReccording=false;
                    volume=0;
                    Thread.sleep(100);
                    recordUtil.stop();
                    tvAddReccord.setText("添加录音");
                    reccordingDialog.dismiss();
                    llAddReccord.setVisibility(View.GONE);
                    rlReccord.setVisibility(View.VISIBLE);
                    tvReccordTime.setText((int)recordTime + "”");
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                break;
        }
        return true;
    }

    //当销毁activity的时候，取消网络请求，这也正是volley框架的优点之一
    @Override
    protected void onDestroy() {
        super.onDestroy();
        orderManager.requestQueue.cancelAll(RepairTypeManager.class);
    }

}
